import { Injectable } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';

@Injectable()
export class RedisdbService {

    public client;

    constructor(private redisService: RedisService) {
        this.getClient();
    }

    private async getClient() {
        this.client = await this.redisService.getClient()
    }

    /**
    * @Description: 封装设置redis缓存的方法
    * @param key {String} key值
    * @param value {String} key的值
    * @param seconds {Number} 过期时间
    * @return: Promise
    */
    public async set(key: string, value: any, seconds?: number) {
        value = JSON.stringify(value);
        if (!this.client) {
            await this.getClient();
        }
        if (!seconds) {
            await this.client.set(key, value);
        } else {
            await this.client.set(key, value, 'EX', seconds);
        }
    }

    /**
    * @Description: 判断该值是否存在
    * @param key {String} key值
    * @return: Promise
    */
    public async exists(key: string) {
        if (!this.client) {
            await this.getClient();
        }
        var data = await this.client.exists(key);
        return data;
    }

    /**
   * @Description: 设置获取redis缓存中的值
   * @param key {String}
   */
    public async get(key: string) {
        if (!this.client) {
            await this.getClient();
        }
        var data = await this.client.get(key);
        if (!data) return;
        return JSON.parse(data);
    }


    /**
    * @Description: 根据key删除redis缓存数据
    * @param key {String}  
    * @return:
    */
    public async del(key: string) {
        if (!this.client) {
            await this.getClient();
        }
        await this.client.del(key);
    }

    /**
     * @Description: 清空redis的缓存
     * @param {type} 
     * @return:
     */
    public async flushall() {
        if (!this.client) {
            await this.getClient();
        }
        await this.client.flushall();
    }
}
